
import 'package:flutter/material.dart';

///定义业务逻辑的抽取类
abstract class BaseBloc{
  void dispose();
}

///在BlocProvider下的子树可以通过BlocProvider.of(xx)获取BaseBloc类型对象
class BlocProvider<T extends BaseBloc> extends StatefulWidget{

  final T bloc;
  final Widget child;

  const BlocProvider({Key key,@required  this.bloc, @required this.child}) : super(key: key);


  @override
  State<StatefulWidget> createState() {
    return _BlocProviderState<T>();
  }

  static T of<T extends BaseBloc>(BuildContext context){
    final type = _typeOf<BlocProvider<T>>();
    BlocProvider<T> provider = context.ancestorWidgetOfExactType(type);

    return provider.bloc;
  }

  static Type _typeOf<T>() => T;


}


class _BlocProviderState<T> extends State<BlocProvider<BaseBloc>>{
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }


  @override
  void dispose() {
    widget.bloc.dispose();
    super.dispose();
  }

}